import md5 from 'md5'
import { message } from '@/libs'

import { loginUser, getUserInfo, registerUser } from '@/api/sys'

export default {
  namespaced: true,
  state: {
    token: '',
    userInfo: {}
  },
  mutations: {
    setToken(state, payload) {
      state.token = payload
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    }
  },
  actions: {
    // 注册事件
    onRegister(context, payload) {
      const { password } = payload
      return registerUser({
        ...payload,
        password: password ? md5(password) : ''
      })
    },
    // 处理登录事件
    onLogin(context, payload) {
      const { password } = payload
      if(payload.code == 204) {
        return payload.code
      }
      loginUser({ ...payload, password: password ? md5(password) : '' })
        .then((res) => {
          const { code, data, message: msg } = res
          if (code == 200) {
            context.commit('setToken', data.token)
            context.dispatch('getInfo')
          }
        })
        .catch((err) => {})
    },
    // 获取用户信息
    getInfo(context, payload) {
      getUserInfo()
        .then((res) => {
          const { code, data } = res
          if (code == 200) {
            const mag = data.vipLevel
              ? `欢迎登陆,尊贵的 VIP${data.vipLevel} 用户 ${data.nickname}`
              : `欢迎 ${data.nickname} 登陆`
            message('success', mag, 5000)
            context.commit('setUserInfo', data)
          }
        })
        .catch((err) => {})
    },
    // 退出登录
    logout(context) {
      context.commit('setUserInfo', {})
      context.commit('setToken', '')
      location.reload()
    }
  }
}
